package com.swn.cm.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.swn.cm.service.StudentPracticeService;
import com.swn.common.base.BaseController;
import com.swn.common.util.DateUtil;
import com.swn.common.util.IID;
import com.swn.common.util.JSONUtil;
import com.swn.common.util.PageListData;

@Controller
@RequestMapping("/student/practice")
public class StudentPracticeController extends BaseController {

	private static Logger logger = Logger
			.getLogger(StudentPracticeController.class);

	@Autowired
	private StudentPracticeService studentPracticeService;

	/**
	 * 分页条件查询学生列表
	 * 
	 * @param start
	 *            第几页
	 * @param length
	 *            每页显示记录条数
	 * @param signupForm
	 *            查询条件(json)
	 * @return
	 */

	@RequestMapping("stulist")
	@ResponseBody
	public Map<String, Object> stulist(Integer start, Integer length,
			String signupForm) {

		// 返回结果map
		Map<String, Object> result = new HashMap<String, Object>();

		Map<String, Object> map = JSONUtil.getMapFromJsonString(signupForm);
		PageListData pageListData = this.getPageListData();
		pageListData.setStart(start);// 当前页数
		pageListData.setLength(length);// 每页条数

		List<Map<String, Object>> stuList = studentPracticeService.stulist(
				pageListData, map);
		int total = pageListData.getCount();// 总条数
		// 总记录数
		result.put("recordsTotal", total);
		// 过滤后的总记录数
		result.put("recordsFiltered", total);
		// 数据列表
		result.put("data", stuList);
		return result;
	}

	@RequestMapping("addStu")
	@ResponseBody
	public String addStu(String signupForm) {
		String result = "fail";
		
		try {
			//解析接送并补充元素
			Map<String,Object> jsonMap = JSONUtil.getMapFromJsonString(signupForm);
			jsonMap.put("id", IID.getIID());
			jsonMap.put("create_time", DateUtil.getDateAndTime());
			int excute = studentPracticeService.saveStu(jsonMap);
			if(excute > 0){
				result = "success";
			}
		} catch (Exception e) {
			logger.error(e);
		}
		
		return result;
	}

	/**
	 * 查询班级列表
	 * 
	 * @return Map<String, Object>
	 */

	@RequestMapping("queryClassList")
	@ResponseBody
	public Map<String, Object> queryClassList() {
		try {
			Map<String, Object> classMapList = studentPracticeService
					.queryClassList();
			return classMapList;
		} catch (Exception e) {
		}
		return null;
	}

	/**
	 * 用户头像上传
	 * 
	 * @param file
	 * @return 1 代表上传成功 0 失败
	 */

	@RequestMapping("uploadFile")
	@ResponseBody
	public Map<String, Object> uploadFile(MultipartFile file,
			HttpServletRequest request, HttpServletResponse response) {
		Map<String, Object> resultMap = new HashMap<String, Object>();

		// 文件上传路径
		String fileName = file.getOriginalFilename();
		String path = request.getSession(false).getServletContext().getRealPath("/uploadFile")
				+ "/" + fileName;
		System.out.println(path);
		// 写入路径
		// 返回固定格式{"code": 0,"msg": "","data": {"src":
		// "http://cdn.layui.com/123.jpg"}}
		FileOutputStream outPutStream = null;
		String newPath = "http://192.168.2.244:8080/common_interface/uploadFile/"+fileName;
		try {
			/*file.transferTo(new File(path));*/
			File newFile = new File(path);
			outPutStream = new FileOutputStream(newFile);
			InputStream inputStream = file.getInputStream();
			byte[] buffer = new byte[1024];
			int bytesRead = -1;
			while ((bytesRead = inputStream.read(buffer)) != -1) {
				outPutStream.write(buffer, 0, bytesRead);
			}
			outPutStream.flush();
			resultMap.put("path", newPath);
			return resultMap;
		} catch (Exception e) {
			resultMap.put("path", newPath);
			e.printStackTrace();
		}finally{
			try {
				outPutStream.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		return resultMap;
	}

	/**
	 * 根据学生id返回学生map
	 * 
	 * @param id
	 * @return
	 */

	@RequestMapping("queryStuById")
	@ResponseBody
	public Map<String, Object> queryStuById(String id) {
		Map<String, Object> resultMap = null;
		try {
			resultMap = studentPracticeService.queryStuById(id);
		} catch (Exception e) {
			logger.error(e);
		}
		return resultMap;
	}
}
